
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router, { asyncRoutes } from '@/router'
import store from '@/store'

import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
    // 开启进度条
    NProgress.start()
    const title = getPageTitle(to.meta.title)
    document.title = title
    // 判断是否登录，是否有token
    const token = store.state.user.token
    if (token) {
        //已经登陆
        if (to.path === '/login') {
            console.log('token去login');
            next('/')
            NProgress.done()//关闭进度条
        } else {
            //触发action中函数，获取用户的信息,存储到vuex
            // 在获取用户信息之前，判断有没有存储过，如果存储了，就不发送请求
            let menus = []
            if (!store.state.user.userInfo.userId) {
                menus = await store.dispatch('user/getUserInfo')
                // menus用户可以访问的页面的权限信息
                console.log('menus', menus);
                // 根据权限信息渲染左侧菜单和动态添加路由
                const filterRoutes=asyncRoutes.filter(item=>{
                    return menus.includes(item.children[0].name)
                })
                console.log('filterRoutes',filterRoutes);

                // 动态追加404路由对象
                filterRoutes.push({ path: '*', redirect: '/404', hidden: true })

                console.log('asyncRoutes',asyncRoutes);

                // 把动态路由的路由添加到vuex中
                store.commit('menus/updateMenus',filterRoutes)

                router.addRoutes(filterRoutes)
                // 动态添加路由是异步，如果说页面没有加载完成直接跳转页面会出现白屏
                // 解决方案next({...to,replace:true})replace:true重新进入页面重新加载
                next({...to,replace:true})
            }

            next()
        }

    } else {
        //未登录
        //includes查找是否包含指定的字符串，有true,没false
        if (whiteList.includes(to.path)) {
            next()
            NProgress.done()
        } else {
            console.log('没有token去login');
            next('/login')
            NProgress.done()//关闭进度条
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
// import store from './store'
// import { Message } from 'element-ui'
// import NProgress from 'nprogress' // progress bar
// import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasGetUserInfo = store.getters.name
//       if (hasGetUserInfo) {
//         next()
//       } else {
//         try {
//           // get user info
//           await store.dispatch('user/getInfo')

//           next()
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done()
// })
